package com.yami.shop.seckill.multishop.listener;

import com.yami.shop.bean.enums.RefundType;
import com.yami.shop.bean.event.ConfirmOrderEvent;
import com.yami.shop.bean.event.UpdateSeckillOrderSkuInfoEvent;
import com.yami.shop.seckill.comment.dao.SeckillMapper;
import com.yami.shop.seckill.comment.dao.SeckillSkuMapper;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.model.SeckillSku;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author yami
 */
@Component
@AllArgsConstructor
public class UpdateSeckillOrderSkuInfoListener {

    private final SeckillMapper seckillMapper;
    private final SeckillSkuMapper seckillSkuMapper;

    @EventListener(UpdateSeckillOrderSkuInfoEvent.class)
    public void addInventory(UpdateSeckillOrderSkuInfoEvent event){
        Seckill seckill = seckillMapper.getSeckillByOrderNumber(event.getOrderNumber());
        SeckillSku seckillSku = seckillSkuMapper.getSeckillSkuBySkuIdAndOrderNumber(event.getSkuId(), event.getOrderNumber());
        if (Objects.equals(event.getRefundType(), RefundType.ALL.value())) {
            // 全部退款，还原全部数量
            seckillMapper.addInventory(seckill.getSeckillId(), event.getProdCount());
            seckillSkuMapper.addInventory(seckillSku.getSeckillSkuId(), event.getProdCount());
        } else {
            // 部分退款，还原退款数量
            seckillMapper.addInventory(seckill.getSeckillId(), event.getGoodsNum());
            seckillSkuMapper.addInventory(seckillSku.getSeckillSkuId(), event.getGoodsNum());
        }
    }
}
